package com.whq.mvc.base.io;

import java.io.*;

public class InputStreamDemo {

    public final static String filePath = "D:\\target\\test.txt";

    public static void main(String[] args) {
        //readFile();
        //readFile1();
        //writeFile();
        //writeFile1();
        writeFile2();
    }

    public static void readFile() {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                String msg = new String(bytes, 0, len, "utf-8");
                System.out.println(msg);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void readFile1(){
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filePath));
            String str = null;
            while ((str = reader.readLine()) != null){
                System.out.println(str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void writeFile() {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            fos.write("吴海强".getBytes("utf-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void writeFile1(){
        FileWriter writer = null;
        try {
            writer = new FileWriter(filePath);
            writer.append("叶丹");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void writeFile2(){
        PrintStream stream = null;
        try {
            stream = new PrintStream(filePath);
            stream.append("love");
            stream.append(" you");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            stream.close();
        }
    }
}
